<script lang="ts" setup>
import type { ActivityItem } from '@/service/app'
import type { CalendarItem } from '@/store'
import dayjs from 'dayjs'
import localeData from 'dayjs/plugin/localeData'
import weekday from 'dayjs/plugin/weekday'
import { ref } from 'vue'
import { MONTH_ENUM, WEEK_ENUM } from '@/constants'
import { useCalendarStore } from '@/store'

/** 使用isScroll 是否滚动，区分在哪个页面 */
const props = defineProps<{
  isScroll?: boolean
  onChange?: (date: string, goodsList: ActivityItem[]) => void
}>()

dayjs.extend(weekday)
dayjs.extend(localeData)
dayjs.locale('zh-cn', {
  weekStart: 1,
})

type ModeType = 'week' | 'month'

interface MonthModeItem {
  date: string | null
  values: ActivityItem[] | null
  isCurrentMonth: boolean
}

const calendarStore = useCalendarStore()

// 本周数据
const weekList = ref<CalendarItem[]>([])
// 今天及之后的日历数据
const afterList = ref<CalendarItem[]>([])
// 控制月和周状态
const mode = ref<ModeType>('week')
// 本月数据
const monthList = ref<MonthModeItem[]>([])
// 当前选中的日历项
const selectedItem = ref(dayjs().format('YYYY-MM-DD'))

// 计算月数据
function getMonthList() {
  const first = dayjs().startOf('month')
  const last = dayjs().endOf('month')

  // 获取当月第一天是星期几
  const firstDayWeekday = first.weekday()

  // 创建月视图数组
  const days = []

  // 添加上个月的填充日期（灰色格子）
  for (let i = 0; i < firstDayWeekday; i++) {
    days.push({ date: null, values: null, isCurrentMonth: false })
  }

  // 添加当月的日期
  for (let i = 0; i < last.date(); i++) {
    const current = first.add(i, 'day')
    const date = current.format('YYYY-MM-DD')
    const values = calendarStore.calendarData[date] ?? []

    days.push({
      date,
      values,
      isCurrentMonth: true,
    })
  }

  monthList.value = days
}

// 计算周数据
function getWeekAndAfterList() {
  const week = dayjs().weekday(-1)

  const currentWeekList: CalendarItem[] = []
  const afterTodayList: CalendarItem[] = []
  for (const [date, values] of Object.entries(calendarStore.calendarData)) {
    if (!dayjs(date).isBefore(week)) {
      const item: CalendarItem = {
        date,
        values,
      }

      afterTodayList.push(item)

      if (currentWeekList.length < 7) {
        currentWeekList.push(item)
      }
    }
  }

  weekList.value = currentWeekList
  afterList.value = afterTodayList
}

// 计算一周数据
onMounted(async () => {
  // 请求日历数据
  await calendarStore.getCalendarData()
  await calendarStore.getConfigType()

  getMonthList()
  getWeekAndAfterList()
})

function handleCardClick() {
  // 如果不是滚动展示，就跳转页面
  if (!props.isScroll) {
    uni.navigateTo({
      url: '/pages/mine/seasonal',
    })
  }
}

function handleTitleClick() {
  if (!props.isScroll) {
    return
  }

  if (mode.value === 'week') {
    mode.value = 'month'
  }
  else if (mode.value === 'month') {
    mode.value = 'week'
  }
}

function handleItemClick(date: string) {
  const isInCurrentMonth = dayjs(date).month() === dayjs().month()
  if (!isInCurrentMonth) {
    return
  }

  const value = calendarStore.calendarData[date].values.goodsId
  selectedItem.value = date
}

function getBgColor(item: Partial<MonthModeItem>) {
  const today = dayjs().format('YYYY-MM-DD')
  if (!item.isCurrentMonth) {
    return '#f5f5f5'
  }

  if (item.date === selectedItem.value) {
    return '#cce7ff'
  }

  if (item.date === today) {
    return '#d9f7be'
  }

  return '#f6ffed'
}

watch(selectedItem, (date) => {
  const goodsList = calendarStore.calendarData?.[date] ?? []
  props.onChange?.(date, goodsList)
}, { immediate: true })
</script>

<template>
  <wd-card class="" @click="handleCardClick">
    <template #title>
      <view class="flex items-center gap-2" @click="handleTitleClick">
        <wd-icon name="calendar" size="24" />
        <view class="font-600">
          {{ MONTH_ENUM[dayjs().month()] }}
        </view>
      </view>
    </template>
    <!-- 时节鉴赏 -->
    <view v-if="isScroll" class="pb-6">
      <!-- 显示周 -->
      <scroll-view v-show="mode === 'week'" scroll-x>
        <view class="flex gap-1">
          <view
            v-for="{ date, values } in afterList"
            :key="date"
            class="w-[80rpx] flex-shrink-0"
          >
            <view class="mb-2 text-center text-dark font-500">
              {{ WEEK_ENUM[dayjs(date).weekday()] }}
            </view>
            <view
              class="h-11 rounded-md bg-gray p-1"
              :style="{
                backgroundColor: getBgColor({ date, isCurrentMonth: true }),
              }"
              @click="handleItemClick(date)"
            >
              <!-- 日期数字 -->
              <view class="mb-1 flex items-center justify-between text-right text-dark">
                <text v-show="selectedItem === date" class="text-[22rpx]">
                  📍
                </text>
                <text v-if="date" class="w-full text-right">
                  {{ dayjs(date).date() }}
                </text>
              </view>

              <view
                v-for="{ goodsId, title, color } in values?.slice(0, 2)"
                :key="goodsId"
                class="w-full flex items-center gap-[1px] text-right text-[12rpx] text-dark-2"
              >
                <view
                  class="h-[3px] w-[3px] rounded-full"
                  :style="{
                    backgroundColor: color,
                  }"
                />
                <text class="flex-grow-1">
                  {{ title.length > 4 ? `${title.slice(0, 3)}...` : title }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <!-- 显示月 -->
      <view v-show="mode === 'month'" class="grid grid-cols-7 w-full gap-1">
        <!-- 星期 -->
        <view
          v-for="(day, index) in WEEK_ENUM"
          :key="index"
          class="mb-2 text-center text-dark font-500"
        >
          {{ day }}
        </view>
        <!-- 日历项 -->
        <view
          v-for="(item, index) in monthList"
          :key="index"
          class="h-11 rounded-md p-1"
          :style="{
            backgroundColor: getBgColor(item),
          }"
          @click="handleItemClick(item.date)"
        >
          <!-- 日期数字 -->
          <view class="mb-1 flex items-center justify-between text-right text-dark">
            <text v-show="selectedItem === item.date" class="text-[22rpx]">
              📍
            </text>
            <text v-if="item.date" class="w-full text-right">
              {{ dayjs(item.date).date() }}
            </text>
          </view>

          <template v-if="item.values">
            <view
              v-for="{ goodsId, title, color } in item.values.slice(0, 2)"
              :key="goodsId"
              class="w-full flex items-center gap-[1px] text-right text-[12rpx] text-dark-2"
            >
              <view
                class="h-[3px] w-[3px] rounded-full"
                :style="{
                  backgroundColor: color,
                }"
              />
              <text class="flex-grow-1">
                {{ title.length > 4 ? `${title.slice(0, 3)}...` : title }}
              </text>
            </view>
          </template>
        </view>
      </view>
    </view>
    <!-- 我的 -->
    <view v-else class="pb-6">
      <view class="grid grid-cols-7 w-full gap-1">
        <view v-for="{ date, values } in weekList" :key="date">
          <view class="mb-2 text-center text-dark font-500">
            {{ WEEK_ENUM[dayjs(date).weekday()] }}
          </view>
          <view
            class="h-11 rounded-md bg-gray p-1"
            :style="{
              backgroundColor:
                date === dayjs().format('YYYY-MM-DD') ? '#d9f7be' : '#f6ffed',
            }"
          >
            <view class="mb-1 text-right text-dark">
              {{ dayjs(date).date() }}
            </view>
            <view
              v-for="{ goodsId, title, color } in values?.slice(0, 2)"
              :key="goodsId"
              class="w-full flex items-center gap-[1px] text-right text-[12rpx] text-dark-2"
            >
              <view
                class="h-[3px] w-[3px] rounded-full"
                :style="{
                  backgroundColor: color,
                }"
              />
              <text class="flex-grow-1">
                {{ title.length > 5 ? `${title.slice(0, 4)}...` : title }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </wd-card>
</template>
